<template>
  <div>
  <el-drawer
    title="设置比例尺"
    :visible="visible"
    direction="rtl"
    :modal="false"
    :wrapperClosable="false"  
    :with-mask="false"
    :size="350"
    :before-close="handleBeforeClose"
    :modal-class="'scale-dialog-modal'"
  >
    <div class="scale-dialog-content">
      <el-form :model="scaleForm" label-width="120px" size="medium" ref="scaleFormRef">
        <div class="scale-info-section">
          <h4>比例尺信息</h4>
          <div class="info-item">
            <span class="label">起点坐标：</span>
            <span class="value" v-if="scaleForm.x1">({{ scaleForm.x1 }}, {{ scaleForm.y1 }})</span>
            <span class="value" v-else>暂无</span>
          </div>
          <div class="info-item">
            <span class="label">终点坐标：</span>
            <span class="value" v-if="scaleForm.x2">({{ scaleForm.x2 }}, {{ scaleForm.y2 }})</span>
            <span class="value" v-else>暂无</span>
          </div>
          <div class="info-item">
            <span class="label">像素距离：</span>
            <span class="value">{{ pixelDistance }} 像素</span>
          </div>
        </div>

        <el-form-item label="比例尺方式" prop="calcSourceWay">
          <el-radio-group v-model="scaleForm.calcSourceWay">
            <el-radio :label="1" style="margin-bottom:10px">通过底图已有数据</el-radio>
            <el-radio :label="2">通过测点最大测值</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="距离方式" prop="calcWay">
          <el-select v-model="scaleForm.calcWay" placeholder="请选择距离计算方式">
            <el-option label="垂直距离" :value="1"></el-option>
            <el-option label="水平距离" :value="2"></el-option>
            <el-option label="直线距离" :value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item 
          label="实际距离" 
          prop="vl"
          v-if="scaleForm.calcSourceWay == 1"
          :rules="[{ required: scaleForm.calcSourceWay == 1, message: '请输入实际距离' }]"
        >
          <div class="distance-input-group">
            <el-input-number
              v-model="scaleForm.vl"
              placeholder="请输入实际距离"
              :min="0"
            ></el-input-number>
          </div>
        </el-form-item>
        <el-form-item  label="距离单位" prop="unit" v-if="scaleForm.calcSourceWay == 1">
          <el-select
              v-model="scaleForm.unit"
              placeholder="单位"
              style="width: 150px; margin-right: 10px;"
            >
              <el-option
                v-for="item in unitList"
                :key="item.id"
                :label="item.unit"
                :value="item.unit"
              ></el-option>
            </el-select>

            <el-tooltip effect="dark" content="配置单位" placement="top">
              <el-button
                type="primary"
                icon="el-icon-setting"
                circle
                size="mini"
                @click="dialogUnitVisble = true"
              ></el-button>
            </el-tooltip>
        </el-form-item>

        <div class="scale-preview" v-if="scaleForm.calcSourceWay == 1 && scaleForm.vl && pixelDistance">
          <h4>比例尺预览</h4>
          <div class="preview-item">
            <span>比例：</span>
            <span class="highlight">1 像素 ≈ {{ (scaleForm.vl / pixelDistance).toFixed(4) }} {{ scaleForm.unit }}</span>
          </div>
          <div class="preview-item">
            <span>换算：</span>
            <span class="highlight">1 {{ scaleForm.unit }} ≈ {{ (pixelDistance / scaleForm.vl).toFixed(2) }} 像素</span>
          </div>
        </div>     
      </el-form>
    </div>

    <div class="drawer-footer">
      <el-button @click="handleCancel" size="small" icon="el-icon-circle-close">取消</el-button>
      <el-button type="primary" @click="handleSave" size="small"   icon="el-icon-circle-check">
        确定
      </el-button>
    </div>
  </el-drawer>


  <el-dialog  title="单位配置" :visible.sync="dialogUnitVisble" 
  width="500px"   v-dialogDrag :before-close="handleChagneUnitList"
  class="unit-config-dialog">
  <div class="unit-config-container">
    <div class="unit-list">
      <div 
        v-for="(item, index) in unitList" 
        :key="item.id" 
        class="unit-item"
        :class="{ 'editing': item.disabled }"
      >
        <div class="unit-content">
          <el-input 
            v-model="item.unit" 
            placeholder="请输入单位" 
            :disabled="!item.disabled" 
            size="small" 
            class="unit-input"
            maxlength="10"
            show-word-limit
          >
            <template #prefix>
              <i class="el-icon-position" style="line-height: 32px;"></i>
            </template>
          </el-input>
          
          <div class="unit-actions">
            <el-button 
              v-show="item.disabled" 
              @click="handleScaleUnitSave(item, index)" 
              type="success" 
              size="small" 
              icon="el-icon-check"
              class="action-btn"
            >
              保存
            </el-button>
            
            <el-button 
              v-show="!item.disabled" 
              @click="handleScaleUnitEdit(item.unit, index)" 
              type="primary" 
              size="small" 
              icon="el-icon-edit"
              class="action-btn"
            >
              编辑
            </el-button>
            
            <el-button 
              @click="handleScaleUnitDel(item.id, index)" 
              type="danger" 
              size="small" 
              icon="el-icon-delete"
              class="action-btn"
            >
              删除
            </el-button>
          </div>
        </div>
        
        <div v-if="item.disabled" class="edit-tip">
          <i class="el-icon-edit"></i>
          编辑中...
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-if="unitList.length === 0" class="empty-state">
        <noData showData/>
      </div>
    </div>
    
    <!-- 新增按钮 -->
    <div class="add-unit-section">
      <el-button 
        @click="handleScaleUnitAdd" 
        type="primary" 
        icon="el-icon-plus" 
        size="small"
        class="add-btn"
      >
        新增单位
      </el-button>
    </div>
  </div>
</el-dialog>
  </div>
</template>

<script>
import {getGraphScaleUnits,GraphScaleUnitAdd,GraphScaleUnitEdit,getGraphScaleUnitsDel} from '@/api/https'
import noData from '@/components/base/noData.vue';
export default {
  name: 'ScaleDialog',
  components:{noData},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    scaleForm: {
      type: Object,
      default: () => ({
        calcSourceWay: 1,
        calcWay: 3,
        vl: '',
        unit: 'm',
        x1: 0,
        y1: 0,
        x2: 0,
        y2: 0,
        referencePointId: '',
        maxValue: 0
      })
    },
    referencePoints: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dialogUnitVisble:false,
      unitList:[]
    }
  },
  computed: {
    pixelDistance() {
      const { x1, y1, x2, y2, calcWay } = this.scaleForm;
      
      if (!x1 || !y1 || !x2 || !y2) return 0;
      
      const dx = x2 - x1;
      const dy = y2 - y1;
      
      switch (calcWay || 3) {
        case 1: // 垂直距离
          return (Math.abs(dy)).toFixed(2);
        case 2: // 水平距离
          return (Math.abs(dx)).toFixed(2);
        case 3: // 直线距离
        default:
          return (Math.sqrt(dx * dx + dy * dy)).toFixed(2);
      }
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.resetFormValidation()
          this.onGraphScaleUnits()
        })
      }
    }
  },
  methods: {
    resetFormValidation() {
      if (this.$refs.scaleFormRef) {
        this.$refs.scaleFormRef.clearValidate()
      }
    },

    handleBeforeClose(done) {
      this.handleCancel()
      done()
    },

    handleCancel() {
      this.resetFormValidation()
      this.saving = false
      this.$emit('cancel')
    },

    handleSave() {
      this.$refs.scaleFormRef.validate((valid) => {
        if (valid) {
          this.saving = true
          
          // 准备提交的数据
          const submitData = {
            ...this.scaleForm,
            pixelDistance: this.pixelDistance,
            scaleRatio: this.pixelDistance / (this.scaleForm.vl || 1)
          }
          
          this.$emit('save', submitData)
        } else {
          this.$message.error('请完善表单信息')
          return false
        }
      })
    },

    handleUnitConfig() {
      this.$emit('unit-config')
    },
    handleChagneUnitList(){
      this.onGraphScaleUnits()
      this.dialogUnitVisble = false
    },
    onGraphScaleUnits(){
        getGraphScaleUnits().then(res=>{
            if(res.isSuccess){
                this.unitList = res.data || []
            }
        })
    },
    handleScaleUnitAdd(){
      this.unitList.push({ unit:'',disabled:true})
    },
    handleScaleUnitSave(data,index){
        if(data.id){
            GraphScaleUnitEdit({
                id:data.id,
                unit:data.unit
            }).then(res=>{
                if(res.isSuccess){
                    this.unitList[index].disabled = false
                    this.$forceUpdate()
                }else{
                    this.$message.error(res.errorMessage) 
                }
            })
        }else{
            GraphScaleUnitAdd({
                id:0,
                unit:data.unit
            }).then(res=>{
                if(res.isSuccess){
                    this.unitList[index].disabled = false
                    this.$forceUpdate()
                }else{
                    this.$message.error(res.errorMessage) 
                }
            })
        }
    },
    handleScaleUnitDel(id,index){
        if(id){
            getGraphScaleUnitsDel({id:id}).then(res=>{
                if(res.isSuccess){
                    this.unitList.splice(index,1)
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        }else{
            this.unitList.splice(index,1)
        }
    },
    handleScaleUnitEdit(name,index){
      this.unitList[index].disabled = true
      this.$forceUpdate()
    },
  }
}
</script>

<style scoped lang="scss">
.scale-dialog-content {
  padding: 20px;
  height: calc(100% - 60px);
  overflow-y: auto;
}

.scale-info-section {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;

  h4 {
    margin: 0 0 10px 0;
    color: #303133;
    font-size: 14px;
    font-weight: 600;
  }

  .info-item {
    display: flex;
    margin-bottom: 8px;
    font-size: 13px;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      color: #606266;
      min-width: 80px;
    }

    .value {
      color: #303133;
      font-weight: 500;
    }
  }
}

.distance-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.scale-preview {
  margin: 20px 0;
  padding: 15px;
  background: #f0f9ff;
  border-radius: 4px;
  border: 1px dashed #91d5ff;

  h4 {
    margin: 0 0 10px 0;
    color: #1890ff;
    font-size: 14px;
    font-weight: 600;
  }

  .preview-item {
    margin-bottom: 8px;
    font-size: 13px;

    &:last-child {
      margin-bottom: 0;
    }

    .highlight {
      color: #1890ff;
      font-weight: 500;
    }
  }
}

.max-value-section {
  margin-top: 20px;
  padding: 15px;
  background: #fff7e6;
  border-radius: 4px;
  border-left: 4px solid #ffa940;

  h4 {
    margin: 0 0 15px 0;
    color: #fa8c16;
    font-size: 14px;
    font-weight: 600;
  }
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  border-top: 1px solid #e8e8e8;
  background: #fff;
  display: flex;
  justify-content: center;
  gap: 12px;
}
.el-drawer__wrapper {
  width: 400px !important;
  height: 100vh !important;
  position: fixed !important;
  top: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  left: auto !important;
  margin-left: 0 !important;
  overflow: hidden !important;
}
.el-upload-list{
  display: none !important;

}


.unit-config-container {
  padding: 10px 0;
}

.unit-list {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 20px;
  
  .unit-item {
    padding: 12px 15px;
    margin-bottom: 10px;
    border: 1px solid #e6e8eb;
    border-radius: 6px;
    transition: all 0.3s ease;
    background: #fafbfc;
    
    &:hover {
      border-color: #409eff;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
      background: #f0f7ff;
    }
    
    &.editing {
      border-color: #67c23a;
      background: #f0f9eb;
    }
  }
  
  .unit-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
  }
  
  .unit-input {
    flex: 1;
    
    :deep(.el-input__inner) {
      border-radius: 4px;
    }
  }
  
  .unit-actions {
    display: flex;
    gap: 8px;
    flex-shrink: 0;
  }
  
  .action-btn {
    padding: 7px 12px;
    border-radius: 4px;
    font-weight: 500;
  }
  
  .edit-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #67c23a;
    display: flex;
    align-items: center;
    gap: 4px;
  }
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
  
  i {
    font-size: 48px;
    margin-bottom: 10px;
    display: block;
  }
  
  p {
    margin: 0;
    font-size: 14px;
  }
}

.add-unit-section {
  text-align: center;
  padding: 15px 0;
  border-top: 1px dashed #dcdfe6;
  
  .add-btn {
    padding: 9px 20px;
    border-radius: 6px;
    font-weight: 500;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    }
  }
}
</style>
